package kr.pe.xissy.soulmate.service;

import java.util.Map;
import java.util.Map.Entry;

import kr.pe.xissy.soulmate.domain.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.keyvalue.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserService extends SoulMateService {

	@Autowired
	public UserService(StringRedisTemplate redisTemplate) {
		super(redisTemplate);
	}

	protected String getKeyString(User user) {
		return getKeyString(user.getEmail());
	}

	protected String getKeyString(String email) {
		return super.getKeyStringPrefix() + email + ":user";
	}

	public User findByEmail(String email) {
		Map<String, String> userInfoMap = hashOperations.entries(getKeyString(email));

		if (userInfoMap.size() <= 0) {
			throw new UsernameNotFoundException(email + " is not found.");
		}

		User userInfo = new User();
		userInfo.setEmail(email);

		for (Entry<String, String> userInfoEntry : userInfoMap.entrySet()) {
			if (userInfoEntry.getKey().equals("password")) {
				userInfo.setPassword(userInfoEntry.getValue());
			} else if (userInfoEntry.getKey().equals("nickName")) {
				userInfo.setNickName(userInfoEntry.getValue());
			}
		}

		return userInfo;
	}

	public void save(User user) {
		String keyString = getKeyString(user);
		hashOperations.put(keyString, "email", user.getEmail());
		hashOperations.put(keyString, "password", user.getPassword());
		hashOperations.put(keyString, "nickName", user.getNickName());
	}

}
